import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:get/get.dart';
import 'package:sabre_sync_fencing/dd_core/dd_other.dart';
import 'package:sabre_sync_fencing/dd_module/dd_launch_and_main/pages/dd_main_tab_page.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../../dd_core/dd_config.dart';
import '../../../dd_core/dd_hive_dao.dart';
import '../../../dd_core/dd_http.dart';
import '../../../dd_core/dd_log_service.dart';
import '../../../dd_core/dd_user_service.dart';
import '../../../dd_models/dd_oauth_model.dart';
import '../../../r.dart';
import '../pages/dd_web_page.dart';

class DDLoginController extends GetxController {
  RxBool isToggled = false.obs;

  String selectLoginType = '';

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    isToggled.close();
    super.onClose();
  }

  Future<void> appleSign() async {
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );
    if (credential.identityToken.dd_isNotEmpty) {
      await loginApi(credential.identityToken!, 3);
    }
  }

  Future<void> fastLogin() async {
    await loginApi(DDAppInfo.getInstance().udid ?? '', 4);
  }

  Future<void> loginApi(String identity, int oauthType) async {
    EasyLoading.show();
    Map<String, dynamic>? result = await oauth(identity, oauthType);
    if (result != null && result['code'] == 0) {
      DDOauthModel authModel = DDOauthModel.fromJson(result["data"]);
      if (authModel.token.dd_isNotEmpty) {
        await DDAppInfo.getInstance().setAuthorizationToken(authModel.token!);
        await Get.find<DDUserService>().setAuthModel(authModel);
        await DDHiveDao.initLocaData(authModel.userinfo?.userId ?? "");
       // await getStrategyApi();
        EasyLoading.dismiss();
        DDLogService().ddGa(page: "loginsuccess");
        navigator?.pushAndRemoveUntil(
          MaterialPageRoute(
            settings: RouteSettings(name: DDRoutesConfig.main),
            builder: (context) {
              return const DDMainTabPage();
            },
          ),
          (route) => route == false,
        );
      } else {
        EasyLoading.dismiss();
        EasyLoading.showToast("login failed");
      }
    } else {
      EasyLoading.dismiss();
    }
  }

  Future<void> getStrategyApi() async {
    Map<String, dynamic>? strategyResult = await getStrategy();
    if (strategyResult != null && strategyResult['code'] == 0) {
      Get.find<DDUserService>().userServiceAccountId =
          strategyResult["data"]["userServiceAccountId"] ?? '';
      if (Get.find<DDUserService>().rongCloudKey.dd_isNotEmpty) {
        Map<String, dynamic>? rongCloudResult = await rongCloudToken();
        EasyLoading.dismiss();
        if (rongCloudResult != null && rongCloudResult['code'] == 0) {
          Get.find<DDUserService>().rongCloudToken = rongCloudResult["data"];
        } else {
          EasyLoading.dismiss();
        }
      } else {
        Map<String, dynamic>? configResult = await getAppConfig();
        if (configResult != null && configResult['code'] == 0) {
          Get.find<DDUserService>().googleKey =
              getDataByName(configResult['data'], 'google_translation_key') ??
                  '';
          Get.find<DDUserService>().rongCloudKey =
              getDataByName(configResult['data'], 'rck') ?? '';
          if (Get.find<DDUserService>().rongCloudKey.dd_isNotEmpty) {
            Map<String, dynamic>? rongCloudResult = await rongCloudToken();
            EasyLoading.dismiss();
            if (rongCloudResult != null && rongCloudResult['code'] == 0) {
              // DDLogService().ddGa(page: "loginsuccess");
              // navigator?.pushAndRemoveUntil(
              //   MaterialPageRoute(
              //     settings: RouteSettings(name: DDRoutesConfig.main),
              //     builder: (context) {
              //       return const DDMainTabPage();
              //     },
              //   ),
              //   (route) => route == false,
              // );
            } else {
              EasyLoading.dismiss();
            }
          }
        } else {
          EasyLoading.dismiss();
        }
      }
    } else {
      EasyLoading.dismiss();
    }
  }

  void onTermOfUseTap() {
    DDLogService().ddGa(page: "terms");
    Get.to(() => DDWebViewPage(
          url: termConditionsUrl,
          title: "Term of Use",
        ));
  }

  void onPrivacyPolicyTap() {
    DDLogService().ddGa(page: "privacy");
    Get.to(() => DDWebViewPage(
          url: privacyPolicyUrl,
          title: "Privacy Policy",
        ));
  }

  void showPrivacyDialog(BuildContext context) {
    Get.dialog(
      barrierDismissible: false,
      Center(
        child: Container(
          decoration: BoxDecoration(
            color: const Color(0xFFD2E8FF),
            borderRadius: BorderRadius.circular(16.0),
          ),
          width: Get.width - 60,
          // height: Get.height / 2,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(
                height: 32,
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: Image.asset(
                  R.assetsImagesAppLogo,
                  width: 64,
                  height: 64,
                  fit: BoxFit.cover,
                ),
              ),
              const SizedBox(
                height: 8,
              ),
              const Text(
                'SabreSync',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w800,
                  color: Color(0xFF53BFD7),
                  letterSpacing: 0.0, // 修改每个文字的间距，单位是逻辑像素
                ),
              ),
              const SizedBox(
                height: 16,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: RichText(
                  text: TextSpan(
                    style: DefaultTextStyle.of(context).style,
                    children: <TextSpan>[
                      const TextSpan(
                        text: 'By using our App you agree with our ',
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 14,
                        ),
                      ),
                      TextSpan(
                        text: 'Term of Use',
                        style: const TextStyle(
                          color: Colors.blue,
                          fontSize: 14,
                        ),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            onTermOfUseTap();
                          },
                      ),
                      const TextSpan(
                        text: ' and ',
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 14,
                        ),
                      ),
                      TextSpan(
                        text: 'Privacy Policy.',
                        style: const TextStyle(
                          color: Colors.blue,
                          fontSize: 14,
                        ),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            onPrivacyPolicyTap();
                          },
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(
                height: 28,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    GestureDetector(
                      onTap: () async {
                        selectLoginType = '';
                        navigator?.pop();
                      },
                      child: Container(
                        width: 100,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFFD2E8FF),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                                fontFamily: 'Readex Pro',
                                color: Color(0x4D000000),
                                fontSize: 14,
                                letterSpacing: 0,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        isToggled.value = true;
                        if (selectLoginType == 'apple') {
                          appleSign();
                        }
                        if (selectLoginType == 'fast') {
                          fastLogin();
                        }
                      },
                      child: Container(
                        width: 163,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFF53BFD7),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Agree and Continue',
                            style: TextStyle(
                                fontFamily: 'Readex Pro',
                                color: Color(0xFFFFFFFF),
                                fontSize: 14,
                                letterSpacing: 0,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),

              // Row(
              //   mainAxisAlignment: MainAxisAlignment.center,
              //   children: [
              //     Expanded(
              //       child:
              //     Container(width: 100,height: 40,
              //       child:
              //       CupertinoButton(
              //         onPressed: () {
              //           navigator?.pop();
              //         },
              //         child:
              //         Text(
              //           'Cancel',
              //           style: FlutterFlowTheme.of(context)
              //               .bodyMedium
              //               .override(
              //             fontFamily: 'Readex Pro',
              //             color: Color(0xFF000000),
              //             fontSize: 14,
              //             letterSpacing: 0,
              //           ),
              //         ),
              //       ),
              //     ),),
              //     Expanded(child: Container(width: 163,height: 40,
              //       child:
              //       CupertinoButton(
              //         onPressed: () {
              //           navigator?.pop();
              //         },
              //         child: Text(
              //           'Agree and Continue',
              //           style: FlutterFlowTheme.of(context)
              //               .bodyMedium
              //               .override(
              //             fontFamily: 'Readex Pro',
              //             color: Color(0xFFFFFFFF),
              //             fontSize: 14,
              //             letterSpacing: 0,
              //           ),
              //         ),
              //       ),
              //     ),),
              //   ],
              // ),
              const SizedBox(
                height: 32,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
